﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO.Ports;
using System.Drawing;
using CIRDiagnoseDevice.DBManage;
using System.Timers;

namespace CIRDiagnoseDevice.Test
{
    class LBJFunTrial
    {
        #   region 全局变量
        private TestRecordManage manage = new TestRecordManage();
        SerialPort OSP3;
        Form form;
        public int ReadedNum = 0; // 记录接收返回数据的次数
        public int CycleTimes = 0;
        private int Cycle = 0;
        private byte[] RBuffer = new byte[500]; // 接收测试仪返回结果
        private DataGridView dataGridView7;
        private byte[] RXBuffer = new byte[2048];//缓冲接收数据
        private List<byte> ListBuffer = new List<byte>();//缓存接收数据
        private LBJAndTrainEndTest Lbj = new LBJAndTrainEndTest();
        private bool Addressed = true;
        private bool Addressed2 = true;
        private InitSerialPort InitPort = new InitSerialPort();
        private int StartIndex; // 指定测试结果填入表中的初始行索引
        public static byte CabNum1, CabNum2, CabNum3, CabNum4;
        public event ThreadEndNotice OnMessageNote;
        private bool ConnSuccese, haveQueryWndPressure, haveAirExhaust, haveReceiveWndAlarm, haveReceiveVolAlarm, haveDeConnection;
        private System.Timers.Timer timer = new System.Timers.Timer();
        private static bool timerEnable = true;
        private string ToolStripInfo;
        public SetToolStripStatusInfo SetToolStripStatusInfo;//此委托的目的是传出现在测试的状态。
        public DateTime startTime; 
        #   endregion

        public string ToolStripInfosx
        {
            get { return ToolStripInfo; }
        }
        private void StartLbjFunTrial()
        {
            if (MessageBox.Show("请选择GSM-R模式运行线路！", "用户操作提示", MessageBoxButtons.OK) == DialogResult.OK)
            {
                Delay(500);
                MessageBox.Show("请先点击“确定”后再用MMI输入客列尾ID号“123456”", "用户操作提示");
                MainFrm.MotherFrm.TestLBJFun = true;
            }
        }

        public static bool TimerEnable
        {
            set { timerEnable = value; }
        }

        public void ClearSoure()
        {
            OSP3.Close();
            OSP3.DataReceived -= new SerialDataReceivedEventHandler(OSP3_DataReceived);
            GC.Collect();
        }

        public void InitParameter()
        {
            ReadedNum = 0;
            CycleTimes = 0;
            Addressed = false;
            Addressed2 = true;
            Array.Clear(RXBuffer, 0, RXBuffer.Length);
            Array.Clear(RBuffer, 0, RBuffer.Length);
            MainFrm.MotherFrm.TestLBJFun = false;
            ListBuffer.Clear();
            OSP3.ReadTimeout = 5000;
            OSP3.DataReceived += new SerialDataReceivedEventHandler(OSP3_DataReceived);
            InitPort.Open(OSP3);
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.Interval = 90000;
            ConnSuccese = false;
            haveQueryWndPressure = false;
            haveAirExhaust = false;
            haveReceiveWndAlarm = false;
            haveReceiveVolAlarm = false;
            haveDeConnection = false;
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (timerEnable == false)
            {
                timer.Enabled = false;
                return;
            }
            if (ConnSuccese == false)
            {
                MessageBox.Show("请先检查KLW试验单元是否开户，并查看串口是否连接上！");
                for (int i = 0; i < 6; i++)
                {
                    FillGridWithJudgeResult(dataGridView7, i + StartIndex, "不合格", false);
                }
                MessageBox.Show("请先点击“确定”再按MMI上的“报警”按键");
                ConnSuccese = true;
                haveQueryWndPressure = true;
                haveAirExhaust = true;
                haveReceiveWndAlarm = true;
                haveReceiveVolAlarm = true;
                haveDeConnection = true;
                ReadedNum = 4;
                Addressed = true;
                timer.Enabled = false;
            }

        }

        public LBJFunTrial(Form form, DataGridView dataGridView7, int startIndex, SerialPort OSP)
        {
            this.form = form;
            this.dataGridView7 = dataGridView7;
            this.StartIndex = startIndex;
            this.OSP3 = OSP;
        }

        //查找帧头和帧尾
        private int FindDataFrameHead(List<byte> arr, byte head1, byte head2, int startIndex, int findLength, bool isFindHead)
        {
            int index = -1;
            int length = 0;
            length = findLength > arr.Count ? arr.Count : findLength;
            for (int i = startIndex; i < length - 1; i++)
            {
                if (arr[i] == head1 && arr[i + 1] == head2)
                {
                    index = i;
                    break;
                }
            }
            return index;
        }

        #region LBJ列尾功能数据处理
        void OSP3_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            while (!MainFrm.MotherFrm.StopTest)
            {
                while (!MainFrm.MotherFrm.Suspend)
                {
                    int readNum = 0;
                    if (MainFrm.MotherFrm.TestLBJFun)
                    {
                        try
                        {
                            try
                            {
                                //readNum = OSP3.BytesToRead;
                                readNum = OSP3.Read(RBuffer, 0, 200);
                            }
                            catch (TimeoutException tex)
                            {
                                if (ConnSuccese == false)
                                {
                                    return;
                                }
                                else if (haveQueryWndPressure == false)
                                {
                                    if (CycleTimes == 0)
                                    {
                                        Lbj.SendWndQuePres(OSP3, CabNum1, CabNum2, CabNum3, CabNum4);
                                        Addressed = false;
                                        CycleTimes++;
                                    }
                                    else
                                    {
                                        Addressed = true;
                                        haveQueryWndPressure = true;
                                        FillGridWithJudgeResult(dataGridView7, 1 + StartIndex, "不合格", false);
                                        MessageBox.Show("请先点击“确定”再长按MMI上的“列尾排风”按键");
                                        CycleTimes = 0;
                                        ReadedNum++;
                                    }
                                }
                                else if (haveAirExhaust == false)
                                {
                                    if (CycleTimes == 0)
                                    {
                                        Lbj.SendAirExhaustBrake(OSP3, CabNum1, CabNum2, CabNum3, CabNum4);
                                        MessageBox.Show("请先点击“确定”再按MMI上的“列尾确认”按键");
                                        Addressed = false;
                                        ReadedNum++;
                                        CycleTimes++;
                                    }
                                    else
                                    {
                                        haveAirExhaust = true;
                                        FillGridWithJudgeResult(dataGridView7, 2 + StartIndex, "不合格", false);
                                        Lbj.SendWndPresAlarm(OSP3, CabNum1, CabNum2, CabNum3, CabNum4);    //发送风压报警命令
                                        Addressed = false;
                                        MessageBox.Show("请听到CIR报风压值后点击“确定”再按MMI上的“列尾确认”按键");
                                        ReadedNum++;
                                        CycleTimes = 0;
                                    }
                                }
                                else if (haveReceiveWndAlarm == false)
                                {
                                    if (CycleTimes == 0)
                                    {
                                        Lbj.SendWndPresAlarm(OSP3, CabNum1, CabNum2, CabNum3, CabNum4);    //发送风压报警命令
                                        Addressed = false;
                                        CycleTimes++;
                                    }
                                    else
                                    {

                                        FillGridWithJudgeResult(dataGridView7, 3 + StartIndex, "不合格", false);
                                        Lbj.SendVoltageAlarm(OSP3, CabNum1, CabNum2, CabNum3, CabNum4);   // 发送电压报警命令
                                        CycleTimes = 0;
                                        MessageBox.Show("请听到CIR报电压不足后先点击“确定”再按MMI上的“列尾确认”按键");
                                        haveReceiveWndAlarm = true;
                                    }
                                }
                                else if (haveReceiveVolAlarm == false)
                                {
                                    if (CycleTimes == 0)
                                    {
                                        Lbj.SendVoltageAlarm(OSP3, CabNum1, CabNum2, CabNum3, CabNum4);   // 发送电压报警命令
                                        CycleTimes++;
                                    }
                                    else
                                    {
                                        CycleTimes = 0;
                                        haveReceiveVolAlarm = true;
                                        FillGridWithJudgeResult(dataGridView7, 4 + StartIndex, "不合格", false);
                                        MessageBox.Show("请先点击“确定”再长按MMI上的“列尾消号”按键");
                                    }
                                }
                            }
                            byte[] temp = new byte[readNum];
                            Array.Copy(RBuffer, 0, temp, 0, readNum);
                            ListBuffer.AddRange(temp);
                        }
                        catch
                        {

                        }
                    }
                }
            }
        }

        public void DealWithData()
        {
            while (!MainFrm.MotherFrm.StopTest)
            {
                while (!MainFrm.MotherFrm.Suspend)
                {
                    if (MainFrm.MotherFrm.TestLBJFun == false)
                    {
                        StartLbjFunTrial();
                        ToolStripInfo = "正在试验LBJ功能";
                        SetToolStripStatusInfo(ToolStripInfo);
                    }
                    if (MainFrm.MotherFrm.TestLBJFun)
                    {
                        try
                        {
                            if (ListBuffer.Count <= 14)
                            {
                                ToolStripInfo = "正在试验LBJ功能:没有接收到数据.";
                                SetToolStripStatusInfo(ToolStripInfo);
                                break;
                            }
                            int startIndex = FindDataFrameHead(ListBuffer, (byte)0x10, (byte)0x02, 0, ListBuffer.Count, true);
                            if (startIndex < 0)
                                continue;
                            int endIndex = FindDataFrameHead(ListBuffer, (byte)0x10, (byte)0x03, startIndex, ListBuffer.Count, false);
                            if (endIndex < 0)
                                continue;
                            int length = endIndex - startIndex + 2;
                            byte[] readData = new byte[length];
                            ListBuffer.CopyTo(startIndex, readData, 0, length);
                            ListBuffer.RemoveRange(0, endIndex + 2);
                            byte[] realData = Lbj.DePacketData(readData);
                            if (realData.Length < 12)
                                continue;
                            if (realData[7] == 0xf9)
                            {
                                if (realData.Length < 26)
                                    continue;
                                if (realData[15] == 0xa5)  //列尾功能
                                {
                                    string cabID = string.Empty;
                                    CabNum1 = realData[17];
                                    CabNum2 = realData[18];
                                    CabNum3 = realData[19];
                                    CabNum4 = realData[20];
                                    cabID = (realData[23] >> 4).ToString() + ((byte)((realData[23] << 4)) >> 4).ToString() + (realData[24] >> 4).ToString() + ((byte)((realData[24] << 4)) >> 4).ToString() +
                                                 (realData[25] >> 4).ToString() + ((byte)((realData[25] << 4)) >> 4).ToString();// +(realData[20] >> 4).ToString() + ((realData[20] << 4) >> 4).ToString();
                                    if (cabID == "123456")
                                    {
                                        if (realData[22] == 0xb5)   //列尾连接
                                        {
                                            Lbj.SendResponseData(OSP3, 0xf9, 0x41);
                                            Lbj.SendLBJConnData(OSP3, CabNum1, CabNum2, CabNum3, CabNum4);
                                            timer.Enabled = true;
                                        }
                                        else if (realData[22] == 0x91)  // 风压查询
                                        {
                                            if (Addressed)
                                            {
                                                timer.Enabled = true;
                                                Lbj.SendResponseData(OSP3, 0xf9, 0x41);
                                                Delay(1000);
                                                FillGridWithJudgeResult(dataGridView7, 1 + StartIndex, "合格", true);
                                                Lbj.SendWndQuePres(OSP3, CabNum1, CabNum2, CabNum3, CabNum4);
                                                Addressed = false;
                                            }
                                        }
                                        else if (realData[22] == 0x24)   //列尾排风
                                        {
                                            if (Addressed)
                                            {
                                                Lbj.SendResponseData(OSP3, 0xf9, 0x41);
                                                haveAirExhaust = true;
                                                FillGridWithJudgeResult(dataGridView7, 2 + StartIndex, "合格", true);
                                                Delay(2500);
                                                Lbj.SendAirExhaustBrake(OSP3, CabNum1, CabNum2, CabNum3, CabNum4);
                                                MessageBox.Show("请先点击“确定”再按MMI上的“列尾确认”按键");
                                                Delay(3000);
                                                Addressed = false;
                                            }
                                        }
                                        else if (realData[22] == 0x31)
                                        {
                                            Delay(3500);
                                            haveReceiveWndAlarm = true;
                                            Lbj.SendResponseData(OSP3, 0xf9, 0x41);
                                            FillGridWithJudgeResult(dataGridView7, 3 + StartIndex, "合格", true);
                                            Lbj.SendVoltageAlarm(OSP3, CabNum1, CabNum2, CabNum3, CabNum4); // 发送电压报警命令
                                            // if (MainFrm.MotherFrm.LbjManufName != "深圳长龙")
                                            {
                                                MessageBox.Show("请听到CIR报电压不足后先点击“确定”再按MMI上的“列尾确认”按键");
                                            }
                                        }
                                        else if (realData[22] == 0xb1)
                                        {
                                            Delay(3500);
                                            haveReceiveVolAlarm = true;
                                            Lbj.SendResponseData(OSP3, 0Xf9, 0x41);
                                            FillGridWithJudgeResult(dataGridView7, 4 + StartIndex, "合格", true);
                                            MessageBox.Show("请先点击“确定”再长按MMI上的“列尾消号”按键");
                                        }
                                        else if (realData[22] == 0x83)
                                        {
                                            haveDeConnection = true;
                                            Lbj.SendResponseData(OSP3, 0xf9, 0x41);
                                            FillGridWithJudgeResult(dataGridView7, 5 + StartIndex, "合格", true);
                                            MessageBox.Show("请先点击“确定”再按MMI上的“报警”按键");
                                            Addressed = true;
                                        }
                                    }
                                }
                                else if (realData[15] == 0x40)
                                {
                                    if (realData[17] == 0x01)
                                    {
                                        if (Addressed)
                                        {
                                            Lbj.SendResponseData(OSP3, 0xf9, 0x00);
                                            FillGridWithJudgeResult(dataGridView7, 6 + StartIndex, "合格", true);
                                            MessageBox.Show("请先取消报警，再点击“确定”");
                                            Delay(5000);
                                            Lbj.SendTrainProtection(OSP3, CabNum1, CabNum2, CabNum3, CabNum4);   // 发送列车防护报警命令
                                            Addressed = false;
                                        }
                                    }
                                }
                                if (realData[8] == 0x00 && ReadedNum == 4)
                                {
                                    if (MainFrm.MotherFrm.LbjManufName != "深圳长龙")
                                    {
                                        if (MessageBox.Show("请观察MMI是否发生列车防护报警", "用户操作提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                        {
                                            FillGridWithJudgeResult(dataGridView7, 7 + StartIndex, "合格", true);
                                            Delay(1000);
                                            Lbj.SendTrainProtectionRemove(OSP3, CabNum1, CabNum2, CabNum3, CabNum4);
                                            ReadedNum++;
                                        }
                                        else
                                        {
                                            FillGridWithJudgeResult(dataGridView7, 7 + StartIndex, "不合格", false);
                                            Delay(5000);
                                            Lbj.SendRoadCrossingAccidentAlarm(OSP3);
                                            ReadedNum++;
                                        }
                                    }
                                    else
                                    {
                                        if (CycleTimes == 0)
                                        {
                                            CycleTimes++;
                                        }
                                        else if (CycleTimes == 1)
                                        {
                                            CycleTimes++;
                                        }
                                        else if (CycleTimes == 2)
                                        {
                                            CycleTimes++;
                                        }
                                        else if (CycleTimes == 3)
                                        {
                                            CycleTimes++;
                                        }
                                        else
                                        {
                                            if (MessageBox.Show("请观察MMI是否发生列车防护报警", "用户操作提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                            {
                                                FillGridWithJudgeResult(dataGridView7, 7 + StartIndex, "合格", true);
                                                Delay(1000);
                                                Lbj.SendTrainProtectionRemove(OSP3, CabNum1, CabNum2, CabNum3, CabNum4);
                                                ReadedNum++;
                                            }
                                            else
                                            {
                                                FillGridWithJudgeResult(dataGridView7, 7 + StartIndex, "不合格", false);
                                                Delay(5000);
                                                Lbj.SendRoadCrossingAccidentAlarm(OSP3);
                                                ReadedNum++;
                                            }
                                            CycleTimes = 0;
                                        }
                                    }
                                }
                            }
                            if (realData[7] == 0xff && realData[8] == 0xf8)//无响应命令的功能试验判断，从应答数据判断
                            {
                                if (realData[9] == 0x41)
                                {
                                    if (ReadedNum == 0 && Addressed == false)
                                    {
                                        if (MessageBox.Show("MMI是否报列尾连接成功语音？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                        {
                                            Addressed = true;
                                            ConnSuccese = true;
                                            timer.Enabled = false;
                                            FillGridWithJudgeResult(dataGridView7, 0 + StartIndex, "合格", true);
                                            MessageBox.Show("请先点击“确定”再按MMI上的“风压查询”按键");
                                            ReadedNum++;
                                        }
                                        else
                                        {
                                            MessageBox.Show("请重新连接列尾！");
                                        }
                                    }
                                    else if (ReadedNum == 1 && Addressed == false)
                                    {
                                        Addressed = true;
                                        haveQueryWndPressure = true;
                                        timer.Enabled = false;
                                        MessageBox.Show("请先点击“确定”再长按MMI上的“列尾排风”按键");
                                        ReadedNum++;
                                    }
                                    else if (ReadedNum == 2 && Addressed == false)
                                    {
                                        Lbj.SendWndPresAlarm(OSP3, CabNum1, CabNum2, CabNum3, CabNum4);    //发送风压报警命令
                                        timer.Enabled = true;
                                        Addressed = false;
                                        // if (MainFrm.MotherFrm.LbjManufName != "深圳长龙")
                                        {
                                            MessageBox.Show("请听到CIR报风压值后点击“确定”再按MMI上的“列尾确认”按键");
                                        }

                                        ReadedNum++;
                                    }
                                    else if (ReadedNum == 3)
                                    {
                                        if (Addressed == false)
                                        {
                                            ReadedNum++;
                                            Addressed = true;
                                        }
                                    }
                                }
                                else
                                {

                                    if (ReadedNum == 4)
                                    {
                                        if (MessageBox.Show("请观察MMI是否发生列车防护报警", "用户操作提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                        {
                                            FillGridWithJudgeResult(dataGridView7, 7 + StartIndex, "合格", true);
                                            Delay(1000);
                                            Lbj.SendTrainProtectionRemove(OSP3, CabNum1, CabNum2, CabNum3, CabNum4);
                                            Delay(5000);
                                            Lbj.SendRoadCrossingAccidentAlarm(OSP3);
                                            ReadedNum++;
                                        }
                                        else
                                        {
                                            FillGridWithJudgeResult(dataGridView7, 7 + StartIndex, "不合格", false);
                                            ReadedNum++;
                                        }
                                    }
                                    else if (ReadedNum == 5)
                                    {
                                        if (Addressed2)
                                        {
                                            Delay(3000);
                                            Lbj.SendRoadCrossingAccidentAlarm(OSP3);  // 发送道口事故报警命令
                                            ReadedNum++;
                                            Addressed2 = false;
                                        }
                                    }
                                    else if (ReadedNum == 6)
                                    {
                                        if (MessageBox.Show("请观察MMI是否发生道口事故报警", "用户操作提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                        {
                                            FillGridWithJudgeResult(dataGridView7, 8 + StartIndex, "合格", true);
                                            Delay(1000);
                                            Lbj.SendRoadCrossingAccidentRemove(OSP3);
                                            Delay(5000);
                                            Lbj.SendConstructionProtectionAlarm(OSP3);
                                            ReadedNum++;
                                        }
                                        else
                                        {
                                            FillGridWithJudgeResult(dataGridView7, 8 + StartIndex, "不合格", false);
                                            Delay(5000);
                                            Lbj.SendConstructionProtectionAlarm(OSP3);
                                            ReadedNum++;
                                        }
                                    }
                                    else if (ReadedNum == 7)
                                    {
                                        Lbj.SendConstructionProtectionAlarm(OSP3);    //发送施工防护报警命令
                                        ReadedNum++;
                                    }
                                    else if (ReadedNum == 8)
                                    {
                                        if (MessageBox.Show("请观察MMI是否发生施工防护报警", "用户操作提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                        {
                                            FillGridWithJudgeResult(dataGridView7, 9 + StartIndex, "合格", true);
                                            Delay(1000);
                                            Lbj.SendConstructionProtectionAlarmRemove(OSP3);
                                            ReadedNum++;
                                        }
                                        else
                                        {
                                            FillGridWithJudgeResult(dataGridView7, 9 + StartIndex, "不合格", false);
                                            ReadedNum++;
                                        }
                                    }
                                    else if (ReadedNum == 9)
                                    {
                                        ReadedNum = 0;
                                        ToolStripInfo = "LBJ功能试验完成";
                                        SetToolStripStatusInfo(ToolStripInfo);
                                        MessageBox.Show("LBJ功能试验完成！");

                                        if (!MainFrm.MotherFrm.IsTestTotal)
                                        {
                                            MainFrm.MotherFrm.ChangeButtonText();
                                        }

                                        MainFrm.MotherFrm.StopTest = true;
                                        MainFrm.MotherFrm.Suspend = true;
                                        OSP3.Close();
                                        MainFrm.MotherFrm.LBJFunTestSaved = false;
                                        if (MainFrm.MotherFrm.IsTestTotal)
                                        {
                                            MainFrm.MotherFrm.WholeFunTrialSaved = false;
                                            MainFrm.MotherFrm.TestTotalSaved = false;
                                            MainFrm.MotherFrm.StopTest = false;
                                            MainFrm.MotherFrm.Suspend = false;
                                        }
                                        if (OnMessageNote != null)
                                        {
                                            //MainFrm.MotherFrm.StopTest = false;
                                            //MainFrm.MotherFrm.Suspend = false;
                                            OnMessageNote(this, ThreadState.End);
                                        }
                                        return;
                                    }
                                }
                            }

                        }
                        catch (TimeoutException e1)
                        {
                            return;
                            // MessageBox.Show(e1.Message);
                        }
                    }
                }
            }
            return;
        }
        #endregion

        //将测试判断结果填写到测试表中
        private void FillGridWithJudgeResult(DataGridView gridview, int rowIndex, string result, bool isGreen)
        {
            gridview.Rows[rowIndex].Cells["试验结果"].Value = result;
            if (isGreen)
                gridview.Rows[rowIndex].Cells["试验结果"].Style.ForeColor = Color.Green;
            else
                gridview.Rows[rowIndex].Cells["试验结果"].Style.ForeColor = Color.Red;
            gridview.Invoke(new MethodInvoker(delegate
            {
                gridview.Refresh();
            }));
        }

        //延时多少毫秒
        public static void Delay(int mSecond)
        {
            int last_start;

            last_start = Environment.TickCount;
            while ((Environment.TickCount - last_start) <= mSecond)
            {
                System.Windows.Forms.Application.DoEvents();
            }
        }
    }
}
